<?php
class User extends CS_Controller
{
    private $user_type_arr = array(
        0               => [UTID_CUSTOMER => '会员'],
        UTID_GROWTH     => [20480 => '分销商', UTID_CUSTOMER => '会员'],
        UTID_MANAGER_L2 => [21504 => '发展商', 20480 => '分销商', UTID_CUSTOMER => '会员'],
        UTID_MANAGER_L1 => [21760 => '二级代理', 21504 => '发展商', 20480 => '分销商', UTID_CUSTOMER => '会员'],
    );
    private $user_type = array();
    private $sex_id = [0 => '保密', 1 => '男', 2 => '女'];

    public function _init()
    {
        $this->load->library('pagination');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('user_related_self_model', 'user_related_self');
        $this->user_type = $this->user_type_arr[0];
        $this->judgeUserType();
    }
    
    public function judgeUserType()
    {
        $res = $this->user_related_self->findOne(['provider_uid' => $this->uid, 'flag' => 1]);
        if ($res->num_rows() > 0) {
            $sellerId = $res->row()->reseller_uid;
            $result = $this->user->findOne(['uid' => $sellerId]);
            if ($result->num_rows() > 0) {
                $sellerType = $result->row()->user_type;
                if ($sellerType & UTID_MANAGER_L1) {
                    $this->user_type = $this->user_type_arr[UTID_MANAGER_L1];
                } elseif ($sellerType & UTID_MANAGER_L2) {
                    $this->user_type = $this->user_type_arr[UTID_MANAGER_L2];
                } elseif ($sellerType & UTID_GROWTH) {
                    $this->user_type = $this->user_type_arr[UTID_GROWTH];
                }
            }
            
        }
    }
    
    public function inquiry($pg=1)
    {
        $user_name = $this->input->get('user_name', true);
        $alias_name = $this->input->get('alias_name', true);
        $data = array();
        if ($user_name || $alias_name) {
            $page_num = 15;
            $num = ($pg-1)*$page_num;
            $config['first_url'] = base_url('user/inquiry').$this->pageGetParam($this->input->get());
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('user/inquiry');
            $config['total_rows'] = $this->user->total($this->input->get());
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_link'] = $this->pagination->create_links();
            $data['page_list'] = $this->user->page_list($page_num, $num, $this->input->get());
            $data['all_rows'] = $config['total_rows'];
            $data['pg_now'] = $pg;
            $data['pg_num'] = $page_num;
            $data['currentThis'] = $this;
        }
        $this->load->view('user/inquiry', $data);
    }

    public function grid($pg = 1)
    {
        $getData = $this->input->get();
        $getData['provider_id'] = $this->uid;
        $page_num = 15;
        $num = ($pg - 1) * $page_num;
        $config['first_url'] = base_url('user/grid') . $this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('user/grid');
        $config['total_rows'] = $this->user->findByCount($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['list'] = $this->user->findPageList($num, $page_num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['user_type'] = $this->user_type;
        $data['sex_id'] = $this->sex_id;
        $data['currentThis'] = $this;
        $this->load->view('user/grid', $data);
    }

    public function add()
    {
        $data['user_type'] = $this->user_type;
        $this->load->view('user/add', $data);
    }

    public function addPost()
    {
        $mobile = $this->input->post('mobile_phone');
        $sexId = $this->input->post('sex_id');
        $aliasName = $this->input->post('alias_name');
        $contacter = $this->input->post('contacter');
        $status = $this->input->post('status');
        $userType = $this->input->post('user_type');
        $password = $this->input->post('password');
        $confirmpassword = $this->input->post('confirmPassword');
        $exist = $this->user->findOne(['mobile_phone' => $mobile], 'uid, mobile_phone');
        if ($exist->num_rows() > 0) {
            $this->ajaxJson(['status' => false, 'msg' => '手机号已经存在']);
        }
        if (!array_key_exists($sexId, $this->sex_id)) {
            $this->ajaxJson(['status' => false, 'msg' => '性别填写不合法~']);
        }
        if (!in_array($status, [0, 1])) {
            $this->ajaxJson(['status' => false, 'msg' => '状态不合法~']);
        }
        if (!array_key_exists($userType, $this->user_type)) {
            $this->ajaxJson(['status' => false, 'msg' => '用户类型不合法~']);
        }
        $parentId = UTID_BEIZHU;
        $res = $this->user_related_self->findOne(['provider_uid' => $this->uid, 'flag' => 1]);
        if ($res->num_rows() > 0) {
            $parentId = $res->row(0)->reseller_uid;
        }
        $userData = [
            'user_type'    => $userType,
            'alias_name'   => $aliasName?:'',
            'mobile_phone' => $mobile,
            'sex_id'       => $sexId,
            'contacter'    => $contacter?:'',
            'parent_id'    => $parentId ?: UTID_BEIZHU,
            'provider_id'  => $this->uid,
            'status'       => $status,
            'created_at'   => date('Y-m-d H:i:s')
        ];
        if (!empty($password)){
            if ($password!= $confirmpassword) {
                $this->ajaxJson(['status' => false, 'msg' => '2次密码不一致']);
            }
            if (strlen($this->input->post('password')) < 6) {
                $this->ajaxJson(['status' => false, 'msg' => '密码长度必须大于6位']);
            }
            $userData['pw'] = md5($password);
        }
        $this->db->trans_begin();
        $uid = $this->user->insert($userData);
        $userAccount = [
            'uid' => $uid,
        ];
        $accountId = $this->user_account->insert($userAccount);
        if (!$uid && !$accountId || $this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $this->ajaxJson(false, '网络繁忙，请稍候再试');
        }
        $this->db->trans_commit();

        $this->ajaxJson(['status' => true, 'msg' => site_url('user/grid')]);
    }

    public function edit($uid)
    {
        $res = $this->user->findOne(['uid' => $uid]);
        $data['res'] = $res->row();
        $data['user_type'] = $this->user_type;
        $this->load->view('user/edit', $data);
    }

    public function editPost()
    {
        $uid = $this->input->post('uid');
        $mobile = $this->input->post('mobile_phone');
        $sexId = $this->input->post('sex_id');
        $aliasName = $this->input->post('alias_name');
        $contacter = $this->input->post('contacter');
        $status = $this->input->post('status');
        $userType = $this->input->post('user_type');
        $result = $this->user->findOne(['uid' => $uid], 'uid, mobile_phone');
        if ($result->num_rows() <= 0) {
            $this->ajaxJson(['status' => false, 'msg' => '违法提交~']);
        }
        $userInfo = $result->row();
        if ($userInfo->mobile_phone != $mobile) {
            $exist = $this->user->findOne(['mobile_phone' => $mobile], 'uid, mobile_phone');
            if ($exist->num_rows() > 0) {
                $this->ajaxJson(['status' => false, 'msg' => '手机号已经存在']);
            }
        }
        if (!array_key_exists($sexId, $this->sex_id)) {
            $this->ajaxJson(['status' => false, 'msg' => '性别填写不合法~']);
        }
        if (!in_array($status, [0, 1])) {
            $this->ajaxJson(['status' => false, 'msg' => '状态不合法~']);
        }
        if (!array_key_exists($userType, $this->user_type)) {
            $this->ajaxJson(['status' => false, 'msg' => '用户类型不合法~']);
        }
        $data = [
            'user_type'    => $userType,
            'alias_name'   => $aliasName?:'',
            'mobile_phone' => $mobile,
            'sex_id'       => $sexId,
            'contacter'    => $contacter?:'',
            'status'       => $status
        ];
        $update = $this->user->update($data, ['uid' => $uid]);
        if (!$update) {
            $this->ajaxJson(['status' => false, 'msg' => '保存失败~']);
        }
        $this->ajaxJson(['status' => true, 'msg' => site_url('user/grid')]);
    }

    /**
     * 验证用户是否注册过。
     */
    public function validateMobilePhone()
    {
        $uid = $this->input->post('uid');
        $mobilePhone = $this->input->post('mobile_phone');
        if (!empty($uid)) {
            $result = $this->user->findOne(['uid' => $uid], 'uid, mobile_phone');
            if ($result->num_rows() <= 0){
                echo 'false';
            }
            $userInfo = $result->row();
            if ($userInfo->mobile_phone != $mobilePhone) {
                $mobilePhone = $this->user->findOne(['mobile_phone' => $mobilePhone], 'uid');
                if ($mobilePhone->num_rows() > 0){
                    echo 'false';
                } else {
                    echo 'true';
                }
            } else {
                echo 'true';
            }
        } else {
            $result = $this->user->findOne(['mobile_phone' => $mobilePhone], 'uid');
            if ($result->num_rows() > 0) {
                echo 'false';
            } else {
                echo 'true';
            }
        }
        exit;
    }
}